package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.entity.Category;
import com.example.mapper.CategoryMapper;
import com.example.mapper.DishMapper;
import com.example.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 * @author xiaoduan
 * @since 2024-07-09
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private DishMapper dishMapper;

    @GetMapping("/page")
    public R page(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        IPage<Category> employeePage = new Page<>(page, pageSize);
        IPage<Category> iPage = categoryService.page(employeePage, wrapper);
        return R.success(iPage);
    }

    @PostMapping
    public R save(@RequestBody Category category) {
        Category category1 = categoryMapper.findByName(category.getName());
        if (category1 != null) {
            return R.error("该分类已存在");
        }
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    @PutMapping
    public R update(@RequestBody Category category) {
        Category category1 = categoryMapper.findByName(category.getName());
        if (category1 != null) {
            return R.error("该分类已存在");
        }
        categoryService.updateById(category);
        return R.success("更新分类成功");
    }

    @DeleteMapping
    public R delete1(@RequestParam String ids) {
        categoryService.removeCategory(ids);
        return R.success("删除类别成功");
    }

    @GetMapping("/list")
    public R list(Category category) {
        // List<Category> list = categoryMapper.findListByType(String.valueOf(category.getType()));
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(category.getType()), Category::getType, category.getType());
        wrapper.orderByAsc(Category::getSort);
        wrapper.orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryMapper.selectList(wrapper);
        return R.success(categories);
    }
}

